package com.jian.exceldaoru.controller;

import com.jian.exceldaoru.service.ExcelService;
import com.jian.exceldaoru.service.ExcelValidate;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * Created by lijian on 2020/10/19 10:09
 */
@Controller
public class ExcelController {
    @Autowired
    private ExcelService excelService;
    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/uploadExcel")
    @ResponseBody
    public String uploadExcel(@RequestParam("file") MultipartFile file,
                              Map<String, Object> map) {
        String name = file.getOriginalFilename();
        if (name.length() < 6 || (!name.substring(name.length() - 5).equals(".xlsx")&&!name.substring(name.length() - 4).equals(".xls"))) {
            return "文件格式错误";
        }
        ExcelBean excelBean = null;
        try {
            //excelBean = ExcelUtils.excelToData(file.getInputStream());
            ExcelValidate excelValidate = new ExcelValidate();
            excelValidate.setColNum(9);
            excelValidate.setDetailTitleLineNum(1);
            excelValidate.setStatisticalTime("统计时间");
            excelValidate.setLineName("线路名称");
            excelValidate.setTabulationTime("制表时间");
            excelValidate.setTabulator("制表人");
            excelValidate.setTabulatingUnit("制表单位");
            excelValidate.setDetailStart("制表时间");
            excelValidate.setDetailEnd("制表单位");
            excelBean = excelService.excelToData(file.getInputStream(),excelValidate);
            if(excelBean.getErrMsg()!=null&&!excelBean.getErrMsg().isEmpty()){
                return excelBean.getErrMsg();
            }
            excelBean.setDateFormat("yyyy/MM/dd HH:mm:ss");
            TableData tableData = new TableData(excelBean);
            if (excelBean == null ) {
                return "导入的数据为空";
            }
            //excel的数据保存到数据库
            try {
//                for (ExcelBean excel : list) {
//                    System.out.println(excel.toString());
//                }
                System.out.println(excelBean);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return e.getMessage();
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
        return "保存成功";
    }

}
